//
//  RegisterViewController.swift
//  todoApp
//
//  Created by lili on 15/2/21.
//  Copyright (c) 2015 ll studio. All rights reserved.
//

import UIKit


typealias callbackfunc=()->Void


class RegisterViewController: UIViewController,SMSVerifyDelegate,UITextFieldDelegate,SecondViewControllerDelegate{
    var  data2:CountryAndAreaCode!
    var  areaArray:NSMutableArray!
    @IBOutlet weak var email: UITextField!
    
    @IBOutlet weak var password: UITextField!
   
    //@IBOutlet weak var repeatPassword: UITextField!
    
    @IBOutlet weak var telephone: UITextField!
    
   // @IBOutlet weak var areaView: UIView!
    @IBOutlet weak var countryButton: UIButton!
    @IBOutlet weak var areaLabel: UILabel!

   
    
    @IBOutlet weak var registerBtn: UIButton!
    @IBOutlet var areaView: UIView!

    var completeBlk : callbackfunc?  // 带初始化方式

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor=BACKGROUND_COLOR
        self.telephone.backgroundColor=BACKGROUND_COLOR
        self.registerBtn.backgroundColor=BUTTON_COLOR
        
        
    
        /* areaView.layer.borderWidth = 0.5
        areaView.layer.borderColor = UIColor.lightGrayColor().CGColor
        areaView.layer.cornerRadius =  5
        areaView.layer.masksToBounds = true
        
*/
        //地区边框颜色
        self.areaView.layer.borderColor = UIColor.lightGrayColor().CGColor
        
        areaArray = NSMutableArray()
        //设置本地区号
        self.setTheLocalAreaCode()
        //获取支持的地区列表
        SMS_SDK.getZone { (state:SMS_ResponseState, array) -> Void in
            if state == SMS_ResponseStateSuccess {//区号数据
                self.areaArray = NSMutableArray(array: array)
            }
            else if SMS_ResponseStateFail == state {
                print("failed to get the area code")
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func backButtonTapped(sender: AnyObject) {
         self.dismissViewControllerAnimated(true, completion: nil)
        
        //self.navigationController?.popViewControllerAnimated(true)
    }
    
    func setTheLocalAreaCode() {
        var locale:NSLocale = NSLocale.currentLocale()
        var dictCodes:NSDictionary = NSDictionary(objects: ["972",
            "93",
            "355",
            "213",
            "1",
            "376",
            "244",
            "1",
            "1",
            "54",
            "374",
            "297",
            "61",
            "43",
            "994",
            "1",
            "973",
            "880",
            "1",
            "375",
            "32",
            "501",
            "229",
            "1",
            "975",
            "387",
            "267",
            "55",
            "246",
            "359",
            "226",
            "257",
            "855",
            "237",
            "1",
            "238",
            "345",
            "236",
            "235",
            "56",
            "86",
            "61",
            "57",
            "269",
            "242",
            "682",
            "506",
            "385",
            "53",
            "537",
            "420",
            "45",
            "253",
            "1",
            "1",
            "593",
            "20",
            "503",
            "240",
            "291",
            "372",
            "251",
            "298",
            "679",
            "358",
            "33",
            "594",
            "689",
            "241",
            "220",
            "995",
            "49",
            "233",
            "350",
            "30",
            "299",
            "1",
            "590",
            "1",
            "502",
            "224",
            "245",
            "595",
            "509",
            "504",
            "36",
            "354",
            "91",
            "62",
            "964",
            "353",
            "972",
            "39",
            "1",
            "81",
            "962",
            "77",
            "254",
            "686",
            "965",
            "996",
            "371",
            "961",
            "266",
            "231",
            "423",
            "370",
            "352",
            "261",
            "265",
            "60",
            "960",
            "223",
            "356",
            "692",
            "596",
            "222",
            "230",
            "262",
            "52",
            "377",
            "976",
            "382",
            "1",
            "212",
            "95",
            "264",
            "674",
            "977",
            "31",
            "599",
            "687",
            "64",
            "505",
            "227",
            "234",
            "683",
            "672",
            "1",
            "47",
            "968",
            "92",
            "680",
            "507",
            "675",
            "595",
            "51",
            "63",
            "48",
            "351",
            "1",
            "974",
            "40",
            "250",
            "685",
            "378",
            "966",
            "221",
            "381",
            "248",
            "232",
            "65",
            "421",
            "386",
            "677",
            "27",
            "500",
            "34",
            "94",
            "249",
            "597",
            "268",
            "46",
            "41",
            "992",
            "66",
            "228",
            "690",
            "676",
            "1",
            "216",
            "90",
            "993",
            "1",
            "688",
            "256",
            "380",
            "971",
            "44",
            "1",
            "598",
            "998",
            "678",
            "681",
            "967",
            "260",
            "263",
            "591",
            "673",
            "61",
            "243",
            "225",
            "500",
            "44",
            "379",
            "852",
            "98",
            "44",
            "44",
            "850",
            "82",
            "856",
            "218",
            "853",
            "389",
            "691",
            "373",
            "258",
            "970",
            "872",
            "262",
            "7",
            "590",
            "290",
            "1",
            "1",
            "590",
            "508",
            "1",
            "239",
            "252",
            "47",
            "963",
            "886",
            "255",
            "670",
            "58",
            "84",
            "1",
            "1 "],
            
            forKeys: ["IL",
                "AF",
                "AL",
                "DZ",
                "AS",
                "AD",
                "AO",
                "AI",
                "AG",
                "AR",
                "AM",
                "AW",
                "AU",
                "AT",
                "AZ",
                "BS",
                "BH",
                "BD",
                "BB",
                "BY",
                "BE",
                "BZ",
                "BJ",
                "BM",
                "BT",
                "BA",
                "BW",
                "BR",
                "IO",
                "BG",
                "BF",
                "BI",
                "KH",
                "CM",
                "CA",
                "CV",
                "KY",
                "CF",
                "TD",
                "CL",
                "CN",
                "CX",
                "CO",
                "KM",
                "CG",
                "CK",
                "CR",
                "HR",
                "CU",
                "CY",
                "CZ",
                "DK",
                "DJ",
                "DM",
                "DO",
                "EC",
                "EG",
                "SV",
                "GQ",
                "ER",
                "EE",
                "ET",
                "FO",
                "FJ",
                "FI",
                "FR",
                "GF",
                "PF",
                "GA",
                "GM",
                "GE",
                "DE",
                "GH",
                "GI",
                "GR",
                "GL",
                "GD",
                "GP",
                "GU",
                "GT",
                "GN",
                "GW",
                "GY",
                "HT",
                "HN",
                "HU",
                "IS",
                "IN",
                "ID",
                "IQ",
                "IE",
                "IL",
                "IT",
                "JM",
                "JP",
                "JO",
                "KZ",
                "KE",
                "KI",
                "KW",
                "KG",
                "LV",
                "LB",
                "LS",
                "LR",
                "LI",
                "LT",
                "LU",
                "MG",
                "MW",
                "MY",
                "MV",
                "ML",
                "MT",
                "MH",
                "MQ",
                "MR",
                "MU",
                "YT",
                "MX",
                "MC",
                "MN",
                "ME",
                "MS",
                "MA",
                "MM",
                "NA",
                "NR",
                "NP",
                "NL",
                "AN",
                "NC",
                "NZ",
                "NI",
                "NE",
                "NG",
                "NU",
                "NF",
                "MP",
                "NO",
                "OM",
                "PK",
                "PW",
                "PA",
                "PG",
                "PY",
                "PE",
                "PH",
                "PL",
                "PT",
                "PR",
                "QA",
                "RO",
                "RW",
                "WS",
                "SM",
                "SA",
                "SN",
                "RS",
                "SC",
                "SL",
                "SG",
                "SK",
                "SI",
                "SB",
                "ZA",
                "GS",
                "ES",
                "LK",
                "SD",
                "SR",
                "SZ",
                "SE",
                "CH",
                "TJ",
                "TH",
                "TG",
                "TK",
                "TO",
                "TT",
                "TN",
                "TR",
                "TM",
                "TC",
                "TV",
                "UG",
                "UA",
                "AE",
                "GB",
                "US",
                "UY",
                "UZ",
                "VU",
                "WF",
                "YE",
                "ZM",
                "ZW",
                "BO",
                "BN",
                "CC",
                "CD",
                "CI",
                "FK",
                "GG",
                "VA",
                "HK",
                "IR",
                "IM",
                "JE",
                "KP",
                "KR",
                "LA",
                "LY",
                "MO",
                "MK",
                "FM",
                "MD",
                "MZ",
                "PS",
                "PN",
                "RE",
                "RU",
                "BL",
                "SH",
                "KN",
                "LC",
                "MF",
                "PM",
                "VC",
                "ST",
                "SO",
                "SJ",
                "SY",
                "TW",
                "TZ",
                "TL",
                "VE",
                "VN",
                "VG",
                "VI"])
        
            let tt:String! = locale.objectForKey(NSLocaleCountryCode) as! String
            var defaultCode:String! =  dictCodes.objectForKey(tt) as! String

            areaLabel.text = "+\(defaultCode)"
            var defaultCountryName:String! = locale.displayNameForKey(NSLocaleCountryCode, value: tt)
            self.countryButton.setTitle(defaultCountryName, forState: UIControlState.Normal)
    }
    
    @IBAction func selectCountry(sender: UIButton) {
        var controller:SectionsViewController = SectionsViewController()
        controller.setAreaArray(areaArray)
        controller.delegate = self
        self.presentViewController(controller, animated: true, completion: nil)
        
    }

    func setSecondData(data: CountryAndAreaCode!) {
        data2 = data
        
        self.areaLabel.text = "+\(data.areaCode)"
        self.countryButton.setTitle(data.countryName, forState: UIControlState.Normal)
    }
    @available(iOS 8.0, *)
    @IBAction func registerButtonTapped(sender: AnyObject) {
        
        
        let userEmail=email.text;
        let userPassword=password.text
       // let userRepeatPassword=repeatPassword.text
        
        //检查是否为空
        //if(userEmail.isEmpty || userPassword.isEmpty||userRepeatPassword.isEmpty)
            if(userEmail!.isEmpty || userPassword!.isEmpty)
        {
            displayMyAlertMessage ("请填上所有信息")
            return
        }
        
        
        //应该加上检查注册地址是否有@
        let countOfPassword = userPassword?.characters.count
        
        if(countOfPassword != 6) {
            displayMyAlertMessage ("请确保密码为6位")
            return
        }

        
        //检查所填内容是否全面
        
        //if(userEmail.isEmpty || userPassword.isEmpty||userRepeatPassword.isEmpty)
        if(userEmail!.isEmpty || userPassword!.isEmpty)        {
            displayMyAlertMessage ("请填上所有信息")
            return
        }
        
        //检查密码是否相同
       /* if (userPassword != userRepeatPassword)
        {
            displayMyAlertMessage("两次密码不相同，请重新输入")
            return
        }
        */
        if (self.alreadyExistAccount(email.text))
        {
//            self.showHudWithTitle("账号已经存在")
            UIAlertView.showWithTitle("账号已经存在", message: "", cancelButtonTitle: "ok", otherButtonTitles: nil, tapBlock: nil)
            return
        }
        else
        {
            var accountObj = AVObject(className: "AccountClass")
            accountObj.setObject(email.text, forKey: "userAccount")
            accountObj.setObject(password.text, forKey: "userPassword")
            accountObj.setObject(email.text, forKey: "acountName")
            accountObj.setObject(false, forKey: "isThirdPartLogin")

            self.showIndicatorWithContent("正在注册")
            
            var ret = accountObj.save() as Bool
            
            self.hideIndicator()
            
            if(ret == true)
            {
                //存储数据
                
                NSUserDefaults.standardUserDefaults().setObject(userEmail, forKey:"userAccount")
                NSUserDefaults.standardUserDefaults().setObject(userEmail, forKey:"acountName")
                NSUserDefaults.standardUserDefaults().synchronize()
                NSUserDefaults.standardUserDefaults().setBool(true, forKey:"isUserLoggedIn")
                //显示注册成功信息
                
                 /*var myAlert=UIAlertController(title:"提示",message:"注册成功",preferredStyle:UIAlertControllerStyle.Alert)
                
                let okAction=UIAlertAction(title:"ok",style:UIAlertActionStyle.Default)
                    {
                        action in self.dismissViewControllerAnimated(true, completion: nil)
                }
                myAlert.addAction(okAction)
                
                self.presentViewController(myAlert, animated: true, completion: nil)
*/
                UIAlertView.showWithTitle("注册成功", message: "", cancelButtonTitle: "ok", otherButtonTitles: nil, tapBlock: nil)
                
                //self.navigationController?.popToRootViewControllerAnimated(true)
                
                //self.performSegueWithIdentifier("toRegister", sender: self)
                self.dismissViewControllerAnimated(true, completion: nil)
                
                self.completeBlk?()
            }
        }
    }

    @IBAction func registerByWithTelephone(sender: UIButton) {
       
        var str:NSString? = self.telephone.text
        if str?.length == 0
        {
            UIAlertView.showWithTitle("请输入手机号", message: "", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
            return
        }
        
        if (self.telephone.text!.componentsSeparatedByString("@").count > 1)
        {
            
            if (Common.isValidateEmail(self.telephone.text) == true)
            {
                if (self.alreadyExistAccount(telephone.text))
                {
                    //            self.showHudWithTitle("账号已经存在")
                    UIAlertView.showWithTitle("邮箱已经存在", message: "", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
                    return
                }else
                {
                    self.performSegueWithIdentifier("EnterPasswordViewController", sender: self)
                }
                return
            }else
            {
                UIAlertView.showWithTitle("请输入正确的邮箱", message: "", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
                return
            }
        }else
        {
            var area = self.areaLabel.text!.stringByReplacingOccurrencesOfString("+", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
            if(area == "86")
            {
                if (Common.isValidateMobile(self.telephone.text) == false)
                {
                    UIAlertView.showWithTitle("请输入正确的手机号码", message: "", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
                    return
                }
            }
            if (self.alreadyExistAccount(telephone.text))
            {
                //            self.showHudWithTitle("账号已经存在")
                UIAlertView.showWithTitle("账号已经存在", message: "", cancelButtonTitle: "ok", otherButtonTitles: nil, tapBlock: nil)
                return
            }
            self.editing = false
            
            var verifycontroller:SMSVerifyViewController = SMSVerifyViewController()
            verifycontroller.phone = telephone.text
            verifycontroller.area = area
            verifycontroller.delegate = self
            
            //        self.navigationController?.pushViewController(verifycontroller, animated: true)
            
            self.showIndicatorWithContent("正在发送")
            
            SMS_SDK.getVerificationCodeBySMSWithPhone(telephone.text, zone: area) { (error:SMS_SDKError!) -> Void in
                self.hideIndicator()
                if (error != nil) {
                    UIAlertView.showWithTitle("", message: ("状态码：\(error.errorCode) ,错误描述：\(error.errorDescription)"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
                } else {
                    //self.navigationController?.pushViewController(verifycontroller, animated: true)
                    //                self.presentViewController(verifycontroller, animated: true, completion: { () -> Void in
                    //
                    //                })
                    self.performSegueWithIdentifier("verifycontroller", sender: self)
                }
            }

        }
        
        
    }
    
    @IBAction func goRegisterBytelephone(sender: UIButton) {
        var controller:RegViewController = RegViewController()
        self.navigationController?.pushViewController(controller, animated: true)
        
    }
    
    //SMSVerifyViewController Delegate
    func verifyCompleted() {
        self.completeBlk?()
        self.presentedViewController?.dismissViewControllerAnimated(false, completion: nil)
        self.navigationController?.popToRootViewControllerAnimated(true)

    }
    @available(iOS 8.0, *)
    func displayMyAlertMessage(userMessage:String)
    {
        var myAlert=UIAlertController(title: "Alert",message:userMessage,preferredStyle:UIAlertControllerStyle.Alert)
        
        let okAction=UIAlertAction(title:"ok",style:UIAlertActionStyle.Default,handler:nil)
        myAlert.addAction(okAction)
        
        self.presentViewController(myAlert, animated: true, completion: nil)
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
        self.view.endEditing(true)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier=="verifycontroller")  {
            
            var detailViewController:SMSVerifyViewController=segue.destinationViewController as! SMSVerifyViewController
            var area = self.areaLabel.text!.stringByReplacingOccurrencesOfString("+", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
            detailViewController.phone = self.telephone.text
            detailViewController.tmpString = "验证短信已发送至+\(area) \(self.telephone.text)"
            
        }else if (segue.identifier=="EnterPasswordViewController")  {
            
            var detailViewController:EnterPasswordViewController=segue.destinationViewController as! EnterPasswordViewController
            detailViewController.phone = self.telephone.text
        }

    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
